<template>

    <div>
        <van-nav-bar title="修改昵称" left-arrow @click-left="onClickLeft" />

        <div class="box">
            <p>为保护您的隐私，您的昵称将用于社区交流和患者沟通。</p>
            <van-field v-model="name" placeholder="请输入用户名" />
            <van-button class="btn" @click="onSubmit" type="primary">确认修改</van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import instance from '../axios/index'
import { showToast } from 'vant';
import router from '../router';
const onClickLeft = () => history.back();
// 获取localStorage值并添加错误处理的函数
const getLocalStorageValue = (key: string): string | null => {
    try {
        const value = localStorage.getItem(key);
        return value;
    } catch (error) {
        return null;
    }
};
const name = ref<string | null>(getLocalStorageValue('user'));
const id = ref<string | null>(getLocalStorageValue('id'));
// 点击修改
const onSubmit = () => {
    if (name.value) {
        const data = {
            id: id.value,
            name: name.value
        }
        instance.post('/api/updateName', data).then((res) => {
            if (res.data.code === 200) {
                showToast('修改成功')
                localStorage.setItem('user', res.data.data.name);
                    router.push('/home/my')
            } else {
                showToast(res.data.message)
            }
        })
    }
}


</script>
<style scoped>
.box {
    height: 92vh;
    background-color: #F5F6F7;
    border: 1px solid #F5F6F7;

    p {
        padding-left: 0.2rem;
        margin-top: 0.1rem;
        font-size: 0.14rem;
        margin-bottom: 0.2rem;
    }

    .btn {
        width: 90%;
        margin-top: 0.2rem;
        margin-left: 5%;
        border-radius: 1rem;
    }
}
</style>